package components.player
{
	import UIFree.ObjectEvent;
	import UIFree.controls.uif_loaderBar;
	import UIFree.uif_Timer;
	import UIFree.uif_component;
	
	import components.c_component;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.TimerEvent;
	import flash.geom.Rectangle;
	import flash.utils.Timer;
	
	import org.osmf.events.TimeEvent;
	
	public class c_playerPanel extends c_component {
		private var _playButton	: c_playButton;
		private var _trackBar	: c_progressBar;
		private var _timer		: Timer;
		public static const HEIGHT: Number = 30;
		public function c_playerPanel(window: c_playerWindow, styleClass:Object='') {
			var inner: Rectangle = window.getInner();
			inner.top = inner.height - HEIGHT;
			
			
			_timer = new Timer(1000);
			super(window, inner.x, inner.y, inner.width, inner.height, styleClass);
			_timer.start();
		}
		
		override public function dispose():void {
			_timer.stop();
			super.dispose();
		}
		
		override protected function listenEvents():void {
			super.listenEvents();
			addEvent(GooglePlayerEvent.STATECHAGE, doStateChange, playerWindow);
			addEvent(uif_component.RESIZE, doResizeWindow, parent);
			addEvent(TimerEvent.TIMER, doRefreshBar, _timer);
		}
		
		private function doRequireTrakBar(e: ObjectEvent): void {
			_trackBar.percent = e.object as Number;
			player.seekTo(player.getDuration() * _trackBar.percent);
		}
		
		private function doStateChange(e: Event): void {
			_playButton.playState = (Object(e).data == 1);
		}
		
		override protected function createComponents():void {
			super.createComponents();
			
			var inner: Rectangle = getInner();
			_playButton = new c_playButton(this, inner.x, inner.y, inner.height, inner.height, app.styles.playButton, doPlayClick);
			inner.left += _playButton.width + getSpace();
			_trackBar	= new c_progressBar(this, inner.x, inner.y, inner.width, inner.height, app.styles.progressBar);
			addEvent(c_progressBar.REQUIRECHANGE, doRequireTrakBar, _trackBar);
		}
		
		protected function doRefreshBar(e: Event): void {
			_trackBar.percent = player.getCurrentTime()/player.getDuration();
		}
		
		protected function doPlayClick(e: Event): void {
			if (!_playButton.playState) player.playVideo();
			else player.pauseVideo();
		}
		
		protected function get player(): Object {
			return playerWindow.player;
		}
		
		protected function get playerWindow(): c_playerWindow {
			return parent as c_playerWindow;
		}
		
		protected function doResizeWindow(e: Event): void {
			refreshBounds();
		}
		
		private function refreshBounds(): void {
			var inner: Rectangle = parentComponent.getInner();
			inner.top = inner.height - HEIGHT;		
			setRect(inner);
			
			inner = getInner();
			inner.left += _playButton.width + getSpace();
			_trackBar.width = inner.width
		}
	}
}